<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 列表 -->
    <el-card>
      <!-- 搜索添加区域 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
            @input="getUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 编辑用户 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row.id)"
            ></el-button>
            <!-- 删除用户 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 分配用户 -->
            <!-- 提示框 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <!-- 按钮 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="allotRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[ 10, 20, 30]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户 对话框-->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <div>
        <!-- 表单 -->
        <el-form :model="addForm" ref="addFormRef" :rules="addUserRules" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <div>
        <el-form :model="editForm" ref="editFormRef" :rules="editFormRules" label-width="60px">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="allotRoleDialogVisible"
      width="30%"
      @close="removeRoleName"
    >
      <div>
        <div>当前用户：{{roleInfo.username}}</div>
        <div class="roleName">当前角色：{{roleInfo.role_name}}</div>
        <div>
          <el-select v-model="roleName" placeholder="请选择">
            <el-option
              v-for="item in roleNameList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setAllotRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //验证邮箱的规则
    let checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (!regEmail.test(value)) {
        //返回一个错误提示

        return callback(new Error("请输入合法的邮箱"));
      }
      callback();
    };
    //验证手机号码的规则
    let checkMobile = (rule, value, callback) => {
      const regMobile = /^1[3456789]\d{9}$/;
      if (!regMobile.test(value)) {
        //返回一个错误提示
        return callback(new Error("请输入合法的手机号码"));
      }
      callback();
    };
    return {
      userList: [],
      total: 0,
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        //当前的页数
        pagenum: 1,
        //当前每页显示多少条数据
        pagesize: 10,
      },
      //添加用户
      addDialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        // password: [{ validator: validatePass, trigger: "blur" }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //修改用户
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 分配角色
      allotRoleDialogVisible: false,
      //用户
      roleInfo: {},
      //角色
      roleNameList: [],
      roleName: "",
    };
  },
  methods: {
    // 获取用户列表
    getUserList() {
      this.$http({
        url: "users",
        params: this.queryInfo,
      }).then((res) => {
        this.userList = res.data.data.users;
        this.total = res.data.data.total;
        this.pagenum = res.data.data.pagenum;
      });
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听页码值 改变的事件
    handleCurrentChange(newPage) {
      // console.log(newpage);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 监听用户状态的改变
    userState(userInfo) {
      console.log(userInfo);
      this.$http
        .put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        .then((res) => {
          if (res.data.meta.status != 200) {
            userInfo.mg_state = !userInfo.mg_state;
            this.$message.error("更新用户状态失败");
            return;
          }
          this.$message.success("更新用户状态成功");
        });
    },
    // 监听添加用户对话框关闭事件
    addDialogClosed() {
      // 用户对话框关闭清空表单
      this.$refs.addFormRef.resetFields();
    },
    //添加用户
    addUser() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return;
        // 发送请求
        this.$http({
          url: "users",
          data: this.addForm,
          method: "post",
        }).then((res) => {
          if (res.data.meta.status != 201) {
            return this.$message.error("添加用户失败");
          }
          this.$message.success("添加用户成功");
          this.addDialogVisible = false;
          this.getUserList();
        });
      });
    },
    //编辑用户
    editUser(id) {
      this.editDialogVisible = true;
      this.$http({
        url: "users/" + id,
      }).then((res) => {
        if (res.data.meta.status != 200) {
          return this.$message.error("获取用户失败");
        }
        this.editForm = res.data.data;
      });
    },
    // 监听编辑用户对话框关闭事件
    editDialogClosed() {
      // 用户对话框关闭清空表单
      this.$refs.editFormRef.resetFields();
    },
    // 编辑用户提交
    editUserInfo() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return;
        // 请求
        this.$http
          .put("users/" + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          })
          .then((res) => {
            if (res.data.meta.status != 200) {
              return this.$message.error("更新用户信息失败");
            }
            this.$message.success("更新用户信息成功");
            this.editDialogVisible = false;
            this.getUserList();
          });
      });
    },
    //删除用户
    deleteUser(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete("users/" + id).then((res) => {
            if (res.data.meta.status != 200) {
              return this.$message.error("删除用户失败");
            }
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getUserList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分配角色
    //获取权限列表
    allotRoleDialog(roleInfo) {
      this.roleInfo = roleInfo;
      this.$http("roles").then((res) => {
        this.roleNameList = res.data.data;
      });
      console.log(this.roleInfo);
      this.allotRoleDialogVisible = true;
    },
    //设置分配角色
    setAllotRole() {
      if (!this.roleName) {
        return this.$message.error("请选择需要分配的权限");
      }
      console.log(this.roleNameList);
      this.$http
        .put(`users/${this.roleInfo.id}/role`, {
          rid: this.roleName,
        })
        .then((res) => {
          this.$message.success(res.data.meta.msg);
          this.getUserList();
          this.allotRoleDialogVisible = false;
        });
    },
    // 清除分配角色初始值
    removeRoleName() {
      this.roleNameList = [];
      this.roleName = "";
    },
  },
  created() {
    this.getUserList();
  },
};
</script>

<style>
.roleName {
  margin: 15px 0;
}
</style>